package cn.didi.feidi.androidorder.fragment.personal;


import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.LatLng;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.databinding.FragmentPersonAddReceiveAddressBinding;
import cn.didi.feidi.androidorder.db.UserAddressDao;
import cn.didi.feidi.androidorder.fragment.FeidiBaseFragment;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.UserAddress;
import cn.didi.feidi.androidorder.util.AppUtil;
import cn.didi.feidi.location.activity.LocationMarkerMapActivity;


/**
 * 新增地址 修改地址
 */
public class PersonAddReceiveAddressFragment extends FeidiBaseFragment {


    public static final int REQUEST_CODE = 2;
    public static final int RESULT_CODE = 3;
    private static final String TAG = "PersonAddReceiveAddress";
    FragmentPersonAddReceiveAddressBinding binding;
    private CheckBox isDefaultAddress;
    private EditText personNameEdit;
    private CheckBox maleCheckBox;
    private CheckBox femaleCheckBox;
    private EditText personPhoneEdit;
    private LinearLayout personLocation;
    private TextView personLocationTv;
    private EditText personAddressDetail;
    private String name;
    private String sex;
    private String phoneNumber;
    private String city;
    private String district;
    private String road;
    private String address;
    private LatLng latLng;
    private UserAddress userAddress;

    private AsyncSession asyncSession;
    private boolean setAddressDefault;


    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static PersonAddReceiveAddressFragment newInstance(Bundle bundle) {
        PersonAddReceiveAddressFragment fragment = new PersonAddReceiveAddressFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_person_add_receive_address, container, false);

        //编辑过来
        Intent intent = getActivity().getIntent();
        userAddress = (UserAddress) intent.getSerializableExtra("userAddress");
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {
        isDefaultAddress = (CheckBox) rootView.findViewById(R.id.person_add_receive_address_checkbox_default_address);

        personNameEdit = (EditText) rootView.findViewById(R.id.person_add_receive_address_person_name);

        maleCheckBox = (CheckBox) rootView.findViewById(R.id.person_add_receive_address_checkbox_male);
        femaleCheckBox = (CheckBox) rootView.findViewById(R.id.person_add_receive_address_checkbox_female);

        personPhoneEdit = (EditText) rootView.findViewById(R.id.person_add_receive_address_person_phone);

        personLocation = (LinearLayout) rootView.findViewById(R.id.person_add_receive_address_person_location_ll);
        personLocationTv = (TextView) rootView.findViewById(R.id.person_add_receive_address_person_location_tv);
        personAddressDetail = (EditText) rootView.findViewById(R.id.person_add_receive_address_address_detail);


        if (userAddress != null) {

            isDefaultAddress.setChecked(userAddress.getDefaultAddress());
            personNameEdit.setText(userAddress.getName());

            if (userAddress.getSex().trim() == "男") {
                maleCheckBox.setChecked(true);
                femaleCheckBox.setChecked(false);
            } else {
                maleCheckBox.setChecked(false);
                femaleCheckBox.setChecked(true);
            }

            personPhoneEdit.setText(userAddress.getPhoneNumber());

            //city + district + road
            personLocationTv.setText(userAddress.getCity() + userAddress.getDistrict() + userAddress.getRoad());
            personLocationTv.setTextColor(Color.parseColor("#212121"));

            personAddressDetail.setText(userAddress.getAddress());

            //还原参数值
            road = userAddress.getRoad();
            city = userAddress.getCity();
            district = userAddress.getDistrict();
            latLng = new LatLng(userAddress.getLatitude(), userAddress.getLongitude());

        }

    }

    @Override
    protected void initData() {
        asyncSession = OrderApplication.getDaoSession().startAsyncSession();
    }

    @Override
    protected void addListener() {

        binding.personAddReceiveAddressCheckboxDefaultAddressParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.personAddReceiveAddressCheckboxDefaultAddress.setChecked(
                        !binding.personAddReceiveAddressCheckboxDefaultAddress.isChecked());
            }
        });

        binding.personAddReceiveAddressCheckboxMaleParent.
                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        maleCheckBox.setChecked(true);
                        femaleCheckBox.setChecked(false);
                    }
                });

        binding.personAddReceiveAddressCheckboxFemaleParent.
                setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        maleCheckBox.setChecked(false);
                        femaleCheckBox.setChecked(true);
                    }
                });

        /**
         * 打开地图
         */
        personLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LocationMarkerMapActivity.class);
                startActivityForResult(intent, REQUEST_CODE);

            }
        });


        getFeidiActionBar().getSettingView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMultiplicationClick()) {
                    return;
                }

                if (getDataFromView()) return;

                final Map<String, String> parameters = new HashMap<>();

                parameters.put("userId", UserManager.getUserId());
                parameters.put("token", UserManager.getToken());
                parameters.put("address", address);
                parameters.put("longitude", latLng.longitude + "");
                parameters.put("latitude", latLng.latitude + "");
                parameters.put("name", name);
                parameters.put("sex", sex);
                parameters.put("phoneNumber", phoneNumber);
                parameters.put("city", city);
                parameters.put("district", district);
                parameters.put("road", road);

                if (isDefaultAddress.isChecked()) {
                    parameters.put("defaultAddress", "true");
                    setAddressDefault = true;

                } else {
                    setAddressDefault = false;
                    parameters.put("defaultAddress", "false");

                }


                if (userAddress != null) {

                    parameters.put("userAddressId", userAddress.getUserAddressId());
                    requestUpdateAddress(parameters);

                } else {

                    requestNewAddress(parameters);
                    asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(UserAddress.class)).
                            where(UserAddressDao.Properties.DefaultAddress.eq(true), UserAddressDao.Properties.UserId.eq(UserManager.getUserId())).
                            build());
                }

            }
        });

    }

    /**
     * 新增的地址
     *
     * @param parameters 请求的参数
     */
    private void requestNewAddress(Map<String, String> parameters) {

        Log.d(TAG, "requestNewAddress: 新增地址  ");
        executeRequest(new AppActionRequest<>(Api.ADD_USER_ADDRESS, parameters, new TypeToken<ApiResponse<UserAddress>>() {
        }.getType(), new ActionCallbackListener<UserAddress>() {
            @Override
            public void onSuccess(String message, final UserAddress address) {

                //如果新增的地址设置为默认地址
                if (setAddressDefault) {

                    asyncSession.setListenerMainThread(new AsyncOperationListener() {
                        @Override
                        public void onAsyncOperationCompleted(AsyncOperation operation) {

                            if (operation.isFailed()) {
                                return;
                            }

                            //设置本地的旧的默认的地址
                            if (operation.getResult() != null) {
                                UserAddress address = ((UserAddress) operation.getResult());
                                address.setDefaultAddress(false);
                                asyncSession.update(address);
                            }
                        }
                    });

                    asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(UserAddress.class)).
                            where(UserAddressDao.Properties.DefaultAddress.eq(true), UserAddressDao.Properties.UserId.eq(UserManager.getUserId())).
                            build());

                }


                asyncSession.insert(address);
                Activity activity = getActivity();
                Intent data = new Intent();
                activity.setResult(3, data);
                activity.finish();

            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "onFailure: " + message);
            }
        }));
    }

    /**
     * 更新用户地址
     *
     * @param parameters
     */
    private void requestUpdateAddress(Map<String, String> parameters) {


        executeRequest(new AppActionRequest<>(Api.UPDATE_USER_ADDRESS, parameters, new TypeToken<ApiResponse<UserAddress>>() {
        }.getType(),
                new ActionCallbackListener<UserAddress>() {
                    @Override
                    public void onSuccess(String message, final UserAddress userAddress) {


                        //如果修改的地址设置为默认地址
                        if (setAddressDefault) {

                            asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                @Override
                                public void onAsyncOperationCompleted(AsyncOperation operation) {

                                    if (operation.isFailed()) {
                                        return;
                                    }

                                    //设置本地的旧的默认的地址
                                    if (operation.getResult() != null) {
                                        UserAddress address = ((UserAddress) operation.getResult());
                                        address.setDefaultAddress(false);
                                        asyncSession.update(address);
                                    }
                                }
                            });

                            asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(UserAddress.class)).
                                    where(UserAddressDao.Properties.DefaultAddress.eq(true), UserAddressDao.Properties.UserId.eq(UserManager.getUserId())).
                                    build());

                        }

                        //更新本地数据库地址
                        asyncSession.update(userAddress);
                        Activity activity = getActivity();
                        Intent data = new Intent();
                        activity.setResult(4, data);
                        activity.finish();


                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        Log.d(TAG, "onFailure: ");
                    }
                }));
    }

    /**
     * @return 输入的数据有误，必能更新或者新建地址
     */
    private boolean getDataFromView() {
        name = personNameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(mActivity, "收货人不能为空", Toast.LENGTH_SHORT).show();
            return true;
        }

        if (binding.personAddReceiveAddressCheckboxFemale.isChecked()) {
            sex = "女";
        } else {
            sex = "男";
        }

        phoneNumber = personPhoneEdit.getText().toString().trim();
        if (!AppUtil.checkPhone(phoneNumber)) {
            Toast.makeText(mActivity, "输入正确手机号", Toast.LENGTH_SHORT).show();
            return true;
        }

        for (int i = 0; i < phoneNumber.length(); i++) {

            if (!PhoneNumberUtils.isISODigit(phoneNumber.charAt(i))) {
                Toast.makeText(mActivity, "输入正确手机号", Toast.LENGTH_SHORT).show();
                return true;
            }
        }

        if (latLng == null) {


            Toast.makeText(mActivity, "请点击收货地址获取定位", Toast.LENGTH_SHORT).show();
            return true;

        }


        address = personAddressDetail.getText().toString().trim();
        if (address == null || address.length() == 0) {
            address = "";
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {
            switch (resultCode) {
                case RESULT_CODE: {
                    /**
                     * 打开地图返回的数据
                     */
                    road = data.getStringExtra("address");
                    city = data.getStringExtra("city");
                    district = data.getStringExtra("district");
                    latLng = data.getParcelableExtra("latLng");
                    if (latLng == null) {
                        makeToast("获取经纬度失败");
                    }
                    personLocationTv.setText(city + district + road);
                    break;
                }
            }
        }
    }
}
